package com.lcq.demo.common.job;

import com.lcq.demo.entity.po.ScheduleTask;
import com.lcq.demo.service.ApiService;
import com.lcq.demo.service.ScheduleTaskLogService;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

import javax.annotation.Resource;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;

public class ApiTaskJob extends QuartzJobBean {

    @Resource
    private ApiService apiService;

    @Resource
    private ScheduleTaskLogService scheduleTaskLogService;

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        ScheduleTask task = new ScheduleTask();
        Integer taskId = (Integer) context.getMergedJobDataMap().get("taskId");
        String taskName = (String) context.getMergedJobDataMap().get("taskName");
        String callTarget = (String) context.getMergedJobDataMap().get("callTarget");
        task.setId(taskId);
        task.setTaskName(taskName);
        task.setCallTarget(callTarget);
        if (taskId == null) {
            throw new JobExecutionException("Task ID is NULL");
        }
        try {
            Date startTime = new Date();
            String s = apiService.fetchData(callTarget);
            System.out.println(s);
            Date endTime = new Date();
            scheduleTaskLogService.logTaskExecution(task, 1, startTime, endTime);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
